package logHandle;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;
import java.util.Map.Entry;

import logHandle.model.LogstashProperty;

/**
 * 
 * @since JDK 1.8
 * @version
 * @author 李萌
 * @Email limeng32@chinaunicom.cn
 * @date 2017年11月6日 下午2:42:57 ;
 * @ClassName ServiceWarden ;
 *
 * @Description ADDFUNCTION ;
 * @Reason ADDREASON;
 *
 */
public class ServiceWarden {

	protected static List<Entry<String, Integer>> list;

	protected static List<Entry<String, Integer>> listStandby;

	protected static String patternCustomized;

	protected static String patternCustomizedStandby;

	/**
	 * 从获取环境变量LOG4J2_XML_PATH执行的路径+/logstash.properties指向的文件或./logstash.properties中的内容找出一个可用的Logstash服务器的IP:port
	 * 
	 * @return
	 */
	protected static Entry<String, Integer> getCompetentOne() {
		LogstashProperty lp = FetchConfig.fetchLogstashProperty4();
		list = FetchConfig.fetchLogstashProperty6(lp.getTargetStr());
		LogstashProperty lpStandby = FetchConfig.fetchLogstashProperty5();
		listStandby = FetchConfig
				.fetchLogstashProperty6(lpStandby.getTargetStr());
		/** 先判断list中是否有可用的entry，如果没有再判断listStandby中是否有可用的entry */
		Entry<String, Integer> ret = null;
		for (Entry<String, Integer> e : list) {
			if (isHostConnectable(e.getKey(), e.getValue())) {
				ret = e;
				break;
			}
		}
		if (ret == null) {
			for (Entry<String, Integer> e : listStandby) {
				if (isHostConnectable(e.getKey(), e.getValue())) {
					ret = e;
					break;
				}
			}
		}
		return ret;
	}

	/**
	 * 从获取环境变量LOG4J2_XML_PATH执行的路径+/logstash.properties指向的文件或./logstash.properties中的内容找出pattern对应的值 <br/>
	 * 或者使用默认的patternlayout
	 * 
	 * @return
	 */
	protected static String getPattern() {
		LogstashProperty lp = FetchConfig.fetchLogstashProperty4();
		patternCustomized = lp.getPattern();
		LogstashProperty lpStandby = FetchConfig.fetchLogstashProperty5();
		patternCustomizedStandby = lpStandby.getPattern();
		return patternCustomized != null ? patternCustomized
				: patternCustomizedStandby != null ? patternCustomizedStandby
						: FetchConfig.patternDefault;
	}

	private static boolean isHostConnectable(String host, int port) {
		Socket socket = new Socket();
		try {
			socket.connect(new InetSocketAddress(host, port), 3000);
		} catch (IOException e) {
			return false;
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
			}
		}
		return true;
	}
}
